package app.pool.client;

import app.pool.utils.FileContentUtils;
import app.pool.utils.MD5Utils;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

@Getter
@Setter
public class EntryInfo {

    private String name;
    private String md5;
    private int start;
    private int length;

    public static FileContentUtils.FileParts toFileParts(List<EntryInfo> entryInfos) {
        List<FileContentUtils.FilePart> fileParts = new ArrayList<>();
        for (EntryInfo entryInfo : entryInfos) {
            FileContentUtils.FilePart filePart = new FileContentUtils.FilePart();
            filePart.setStart(entryInfo.getStart());
            filePart.setLength(entryInfo.getLength());
            fileParts.add(filePart);
        }
        return new FileContentUtils.FileParts(fileParts);
    }

    public static List<EntryInfo> fromZipfile(File jarfile, byte[] filecontent) throws IOException {

        try (ZipFile zipSrc = new ZipFile(jarfile);) {
            List<EntryInfo> entryInfos = new ArrayList<>();

            int lastIndex = 0;

            Enumeration srcEntries = zipSrc.entries();
            while (srcEntries.hasMoreElements()) {

                ZipEntry entry = (ZipEntry) srcEntries.nextElement();
                int size = 1024 * 100;
                if (entry.getSize() == entry.getCompressedSize()
                        && entry.getSize() > size) {
                    byte[] array = IOUtils.toByteArray(zipSrc.getInputStream(entry));
                    int index = indexContent(filecontent, array, lastIndex);
                    if (index != -1) {
                        lastIndex = index;

                        EntryInfo entryInfo = new EntryInfo();
                        entryInfo.setName(entry.getName());
                        entryInfo.setMd5(MD5Utils.getMD5(array));
                        entryInfo.setStart(index);
                        entryInfo.setLength(array.length);
                        entryInfos.add(entryInfo);

                        System.out.println("文件中,大小大于" + size + "的Entry,name=" + entryInfo.getName() + ", md5=" + entryInfo.getMd5());

                    }

                }

            }

            return entryInfos;

        }

    }

    private static int indexContent(byte[] filecontent, byte[] array, int startIndex) {
        for (int i = startIndex; i < filecontent.length - array.length; i++) {
            boolean allsame = true;
            for (int j = 0; j < array.length; j++) {
                if (filecontent[i + j] != array[j]) {
                    allsame = false;
                    break;
                }
            }

            if (allsame) {
                return i;
            }
        }

        return -1;
    }
}
